
import { isEmpty, setStorage, getStorage, removeStorage } from './common-api'

const api = { isEmpty, setStorage, getStorage, removeStorage }

export default {
  /* 最近一次服务请求时间 */
  lastconnectKey: 'system:web:last-connect-time:key',
  setLastConnectTime(){
    api.setStorage(this.lastconnectKey, new Date());
  },

  /* 记住token */
  tokenKey: 'system:web:token:key',
  setToken(data) {
    if (!api.isEmpty(data)) {
      api.setStorage(this.tokenKey, data);
    }
  },
  getToken() {
    const data = api.getStorage(this.tokenKey);
    if (!api.isEmpty(data)) {
      return data;
    }
  },
  hasToken() {
    
    // token 存在时，校验是否失效
    if(!api.isEmpty(this.getToken())){
      const lastConnectTime = api.getStorage(this.lastconnectKey);

      // 存在服务连接记录
      if(lastConnectTime){
        const nowTime = new Date().getTime();
        // 计算时差，并转换成秒
        const difftime = (nowTime - lastConnectTime.getTime()) / 1000;
        // 时差超过2h，表示 token 过期
        return difftime < 2 * 60 * 60 * 1000;
      }
    }
    return false;
  },
  delToken() {
    api.removeStorage(this.tokenKey);
    return this
  },

  /* 记住用户名和密码 */
  rememberKey: 'system:web:remember:key',
  setRemember(data) {
    api.setStorage(this.rememberKey, data);
  },
  getRemember() {
    const data = api.getStorage(this.rememberKey);
    if (!api.isEmpty(data)) {
      return data;
    }
  },
  delRemember() {
    api.removeStorage(this.rememberKey);
  },

  /* 记住用户信息 */
  userKey: 'system:web:user:key',
  setUser(data) {
    if (!api.isEmpty(data)) {
      api.setStorage(this.userKey, data);
    }
  },
  getUser() {
    const data = api.getStorage(this.userKey);
    if (!api.isEmpty(data)) {
      return data;
    }
  },
  delUser() {
    api.removeStorage(this.userKey);
    return this
  },

  /* 记住菜单信息 */
  menusKey: 'system:web:menus:key',
  setMenus(data) {
    if (!api.isEmpty(data)) {
      api.setStorage(this.menusKey, data);
    }
  },
  getMenus() {
    const data = api.getStorage(this.menusKey);
    if (!api.isEmpty(data)) {
      return data;
    }
  },
  delMenus() {
    api.removeStorage(this.menusKey);
    return this
  },
}
